import React, { Component } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, Table, Modal, Select, DatePicker, Radio, Divider } from 'antd';
import styles from './List.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import globalConstant from '../../utils/globalConstant';
import ShowOrderInfo from './ShowOrderInfo';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ userBroad, general, loading }) => ({
  userBroad,
  general,
  loading: loading.models.userBroad,
}))
@Form.create()
export default class BroadbandManagement extends Component {
  state = {
    id: undefined,
    showBusinessInfoVisible: false,
    pageNum: globalConstant.paging.defaultPageNum,
    pageSize: globalConstant.paging.defaultPageSize,
    form: {},
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userBroad/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
    dispatch({
      type: 'general/getDistrictList',
    });
  }
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    })
    dispatch({
      type: 'userBroad/fetch',
      payload: params,
    });
  }
  handleSearch = (e) => {
    e.preventDefault();
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log(fieldsValue);
      const invalidValue = fieldsValue.invalidDate || undefined;
      const effectiveValue = fieldsValue.effectiveDate || undefined;
      dispatch({
        type: 'userBroad/fetch',
        payload: {
          effectiveTimeEnd: effectiveValue && effectiveValue[1].valueOf(),
          effectiveTimeStart: effectiveValue && effectiveValue[0].valueOf(),
          invalidTimeEnd: invalidValue && invalidValue[1].valueOf(),
          invalidTimeStart: invalidValue && invalidValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          networkUseStatus: fieldsValue.networkUseStatus === -1 ? null : fieldsValue.networkUseStatus,
        },
      });
      this.setState({
        form: {
          effectiveTimeEnd: effectiveValue && effectiveValue[1].valueOf(),
          effectiveTimeStart: effectiveValue && effectiveValue[0].valueOf(),
          invalidTimeEnd: invalidValue && invalidValue[1].valueOf(),
          invalidTimeStart: invalidValue && invalidValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          networkUseStatus: fieldsValue.networkUseStatus === -1 ? null : fieldsValue.networkUseStatus,
        },
      });
    });
  }
  handleNearOutOfDateSearch = () => {
    const { dispatch } = this.props;
    const currentTime = moment(Date.now()).valueOf();
    const objectTime = moment(Date.now()).add(7, 'd').valueOf()
    dispatch({
      type: 'userBroad/fetch',
      payload: {
        invalidTimeEnd: currentTime || 0,
        invalidTimeStart: objectTime || 0,
      },
    });
    this.setState({
      form: {
        invalidTimeEnd: currentTime || 0,
        invalidTimeStart: objectTime || 0,
      },
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      form:{},
    });
    dispatch({
      type: 'userBroad/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  showInfo = (value) => {
    this.setState({
      showBusinessInfoVisible: true,
      id: value.id,
    });
  };

  handleInfoBusinessModalCancel =() => {
    this.setState({
      showBusinessInfoVisible: false,
    });
  }
  handleRefreshList =() => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userBroad/fetch',
      payload: {
        pageNum: this.state.pageNum,
        pageSize: this.state.pageSize,
        ...this.state.form,
      },
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const districtArray = [{ id: -1, value: '全部' }];
    this.props.general.districtList.map((item) => {
      return (
        districtArray.push({ id: item.id, value: item.districtName })
      );
    });
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input placeholder="请输入搜索关键字" />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="状态">
              {getFieldDecorator('networkUseStatus')(
                <Select>
                  {
                    globalConstant.networkUseStatus.map((item) => {
                      const optionArray = [];
                      if (item.id !== -1) {
                        optionArray.push(
                          <Option
                            key={item.id.toString()}
                            value={item.id}
                          >{item.value}
                          </Option>
                        );
                      }
                      return optionArray;
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="区域">
              {getFieldDecorator('districtId')(
                <Select placeholder="请选择">
                  {
                    districtArray.map((item, index) => {
                      return (
                        <Option
                          key={index.toString()}
                          value={item.id}
                        >
                          {item.value}
                        </Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字类型">
              {getFieldDecorator('keywordsNames')(
                <Select
                  mode="multiple"
                >
                  <Select.Option value="userName">用户名</Select.Option>
                  <Select.Option value="userAddress">居住地址</Select.Option>
                  <Select.Option value="userMobile">手机</Select.Option>
                  <Select.Option value="userIdcard">身份证</Select.Option>
                  <Select.Option value="userEmail">邮箱</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="生效日期">
              {getFieldDecorator('effectiveDate')(
                <DatePicker.RangePicker
                  format={globalConstant.dateFormat}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="到期日期">
              {getFieldDecorator('invalidDate')(
                <DatePicker.RangePicker
                  format={globalConstant.dateFormat}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Button style={{ marginLeft: 8 }} type="primary" htmlType="submit">查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
          </Col>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Button style={{ marginLeft: 8 }} type="primary" icon="search" onClick={() => { this.handleNearOutOfDateSearch(); }}>查看快过期宽带</Button>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const { loading, userBroad: { userBroadList } } = this.props;
    const { showBusinessInfoVisible, id } = this.state;
    const columns = [
      {
        title: '用户ID',
        dataIndex: 'userId',
      },
      {
        title: '姓名',
        dataIndex: 'userNameTrasient',
      },
      {
        title: '手机',
        dataIndex: 'userMobileTrasient',
      },
      {
        title: '地址',
        dataIndex: 'districtNameTrasient',
      },
      {
        title: '套餐名称',
        dataIndex: 'productName',
      },
      {
        title: '区域',
        dataIndex: 'districtName',
      },
      {
        title: '带宽',
        dataIndex: 'speedTrasient',
      },
      {
        title: '生效时间',
        dataIndex: 'effectiveTime',
        render: (text) => {
          return text !== null ? moment(text).format('YYYY-MM-DD') : '时间无效';
        },
      },
      {
        title: '失效时间',
        dataIndex: 'invalidTime',
        render: (text) => {
          return text !== null ? moment(text).format('YYYY-MM-DD') : '时间无效';
        },
      },
      {
        title: '手动更改',
        dataIndex: 'isHandOperate',
        render: (text) => {
          return (text === true ? '是' : '否');
        },
      },
      {
        title: '状态',
        dataIndex: 'networkUseStatus',
      },
      {
        title: '操作',
        key: 'key',
        render: (text, record, index) => {
          return (
            <div key={index.toString()}>
              <Button type="primary" onClick={() => { this.showInfo(text); }} >
                查看详情
              </Button>
            </div>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: userBroadList && userBroadList.totals,
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
      ...globalConstant.pagingFormat,
    };
    return (
      <PageHeaderLayout title="用户宽带管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            <Divider />
            <Table
              bordered
              loading={loading}
              rowKey={record => record.id}
              dataSource={userBroadList && userBroadList.items}
              columns={columns}
              pagination={paginationProps}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          visible={showBusinessInfoVisible}
          title="查看详情"
          footer={null}
          width="60%"
          onCancel={() => this.handleInfoBusinessModalCancel()}
          destroyOnClose
        >
          <ShowOrderInfo refreshList={this.handleRefreshList.bind(this)} data={id} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
